import {LoginLayout, MInput} from '@/views/login/components/LoginContainer.jsx';
import styled from 'styled-components';
import {useEffect, useRef, useState} from 'react';
import {Checkbox, Form, Input, message} from 'antd';
import {getImageUrl, debounce} from '@/utils/utils.js';
import {b64_md5} from '@/utils/md5Ver2.2';
import {login as submitLogin, sendSmscode} from '@/api/user';
import {useNavigate, useParams, useSearchParams} from 'react-router-dom';
import _ from 'lodash';
import useConfigStore from '@/store/useConfigStore.js';

const LoginFormContainer = styled.div`
    width: 480px;
    background-color: #fff;
    border-radius: 25px;
    box-shadow: 0 0 16px 0 #99989899;
    overflow: auto;
    height: 510px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    box-sizing: border-box;
    padding: 80px 51px 0px 51px;

    .tab-list {
        display: flex;
        position: relative;
        width: fit-content;
        margin-left: 10px;
        padding-bottom: 10px;
        margin-bottom: 42px;

        .active {
            content: "";
            position: absolute;
            left: 0;
            top: 100%;
            height: 4px;
            background-color: #53B332;
            border-radius: 4px;
            //margin-top: 10px;
            z-index: 10;
            transition: all 0.3s;
        }

        &::after {
            content: "";
            width: 100%;
            position: absolute;
            left: 0;
            top: 100%;
            height: 4px;
            background-color: #f5f9fe;
            border-radius: 4px;
            //margin-top: 10px;
        }

        .tab-item {
            color: #1c1c1c;
            font-size: 22px;
            font-weight: 700;
            line-height: 22px;
            margin-right: 42px;
            cursor: pointer;

            &:last-of-type {
                margin-right: 0;
            }
        }

    }

    .code {
        color: #53b332;
        font-size: 14px;
        font-weight: 400;
        line-height: 12px;
        cursor: pointer;
        user-select: none;
    }

    .login-btn {
        width: 100%;
        height: 56px;
        opacity: 0.8;
        font-size: 22px;
        font-weight: 400;
        color: #fff;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        background: linear-gradient(90deg, #06a0fd 0%, #37eab4 100%);

        &:hover {
            background: linear-gradient(90deg, #06a0fdce 0%, #37eab4ce 100%);
        }
    }

    .operator {
        display: flex;
        justify-content: space-between;
        margin-top: 29px;
        align-items: center;
        height: 22px;

        .label {
            color: #666666;
            font-size: 14px;
            font-weight: 400;
            line-height: 16px;
        }

        .ant-checkbox .ant-checkbox-inner {
            border: 1.29px solid #53B332;
            border-radius: 0;
        }

        .ant-checkbox-checked .ant-checkbox-inner {
            background: #53B332 !important;
        }

        .tips {
            display: flex;
            flex: 1;
            justify-content: flex-end;

            .tips-item {
                color: #75c25b;
                font-size: 14px;
                font-weight: 400;
                line-height: 14px;
                margin-right: 31px;
                cursor: pointer;

                &:last-of-type {
                    margin-right: 0;
                }
            }
        }
    }
`;

function TabList({activeTab, setActiveTab, tabList}) {
  const findIndex = tabList.findIndex(item => item.value === activeTab);
  const [activeStyle, setActiveStyle] = useState({});
  useEffect(() => {
    const active = document.querySelector('.isActive');
    setActiveStyle({
      width: active.offsetWidth,
      left: active.offsetLeft,
    });
  }, [findIndex]);
  return (<>
    <div className="tab-list">
      {tabList.map((item, index) => {
        return (<div key={index} className={`tab-item ${item.value === activeTab
            ? 'isActive'
            : ''}`} onClick={() => {
          setActiveTab(item.value);
        }}>{item.label}</div>);
      })}
      {findIndex !== -1 && <span className="active" style={activeStyle}></span>}
    </div>
  </>);
}

function CodeBtn({isSendCode, countDown, sendCode}) {
  return (<>
    <div className="code" onClick={sendCode}>{isSendCode
        ? '发送验证码'
        : countDown + 's后可重新发送'}</div>
  </>);
}

function LoginPage() {
  const [activeTab, setActiveTab] = useState(1);
  const [form] = Form.useForm();
  const [isShowPwd, setIsShowPwd] = useState(true);
  const [isSendCode, setIsSendCode] = useState(true);
  const [countDown, setCountDown] = useState(60);
  const setUserInfo = useConfigStore(state => state.setUserInfo);
  const navigate = useNavigate();
  const params = useParams();
  const searchParams = useSearchParams();
  console.log(params, searchParams);
  const formRef = useRef();
  const [rememberPassword, setRememberPassword] = useState(false);
  const password = Form.useWatch('password', form);
  const [tabList, setTabList] = useState(
      [
        {
          label: '账号登录',
          value: 1,
        },
        {
          label: '短信登录',
          value: 2,
        },
      ],
  );
  useEffect(() => {
    formRef.current.nativeElement.addEventListener('keypress', handleKeyDown);
    initLoginFields();
    // return () => {
    //   formRef.current.nativeElement.removeEventListener('keypress', handleKeyDown)
    // }
  }, []);

  function handleKeyDown(e) {
    if (e.key === 'Enter') {
      handleLogin();
    }
  }

  function initLoginFields() {
    const mobile = localStorage.getItem('mobile');
    const password = localStorage.getItem('password');
    if (mobile && password) {
      form.setFieldsValue({
        mobile: localStorage.getItem('mobile'),
        password: atob(localStorage.getItem('password')),
      });
      setRememberPassword(true);
    }
  }

  const handleLogin = _.debounce(() => {
    form.validateFields().then(async values => {
      const params = {
        mobile: values.mobile,
        login_type: activeTab,
        extra: activeTab === 1 ? b64_md5(values.password) : values.code,
      };
      const res = await submitLogin(params);
      if (res.result.status_info.status_code !== 100) {
        message.open({
          type: 'error',
          content: res.result.status_info.status_message,
        });
        return;
      }
      setUserInfo(res.result.user_info);
      localStorage.setItem('releaseToken', res.result.user_info.access_token);
      if (activeTab === 1) {
        if (rememberPassword) {
          localStorage.setItem('mobile', values.mobile);
          localStorage.setItem('password', btoa(values.password));
        } else {
          localStorage.removeItem('mobile');
          localStorage.removeItem('password');
        }
      }
      navigate('/home');
    }).catch(errorInfo => {
      // 验证失败
      console.log('验证失败:', errorInfo);
    });
  }, 200);

  function handleChange(value) {
    setActiveTab(value);
    // form.setFieldValue('password', '')
    // form.setFieldValue('code', '')
  }

  const sendCode = debounce(() => {
    if (!isSendCode) return;
    form.validateFields(['mobile']).then(async values => {
      // 验证通过
      console.log(values);
      const res = await sendSmscode(values.mobile, 1);
      if (res.result.status_info.status_code !== 100) {
        message.open({
          type: 'error',
          content: res.result.status_info.status_message,
        });
        return;
      }
      setIsSendCode(false);
      const timer = setInterval(() => {
        setCountDown((value) => {
          if (value === 0) {
            clearInterval(timer);
            setIsSendCode(true);
            return 60;
          }
          return value - 1;
        });
      }, 1000);
    }).catch(errorInfo => {
      // 验证失败
      console.log('验证失败:', errorInfo);
    });
  }, 200);
  return (<>
    <LoginLayout>
      <LoginFormContainer>
        <TabList activeTab={activeTab} setActiveTab={handleChange}
                 tabList={tabList}/>
        <Form
            form={form}
            ref={formRef}
        >
          <Form.Item
              name="mobile"
              style={{marginBottom: '27px'}}
              validateTrigger="onBlur"
              rules={[
                {required: true, message: '请输入有效的手机号码'},
                {
                  validator: (_, value) => {
                    // const notNumberReg = /[^\d]+/g
                    const mobileReg = /^1[3-9][\d]{9}$/g; //手机号验证正则表达式
                    // if (value && notNumberReg.test(value)) {
                    //   form.setFieldValue(['mobile'], value.replace(notNumberReg, ''))
                    //   return Promise.reject(new Error('请输入有效的手机号码'));
                    // }
                    if (value && !mobileReg.test(value)) {
                      return Promise.reject(new Error('请输入有效的手机号码'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-phone" placeholder="请输入手机号码"
                    maxLength={11}></MInput>
          </Form.Item>
          {activeTab === 1 ? <Form.Item
              name="password"
              style={{marginBottom: '41px'}}
              validateTrigger="onBlur"
              rules={[
                {required: true, message: '密码不能为空字符'},
                {
                  validator: (_, value) => {
                    const passwordReg = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,20}$|^(?=.*[a-zA-Z])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,20}$|^(?=.*[0-9])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,20}$/; //手机号验证正则表达式
                    if (value && !passwordReg.test(value)) {
                      return Promise.reject(new Error(
                          '格式错误，需含数字、字母和符号中至少2种，8-20位'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-lock" placeholder="请输入登录密码"
                    type={isShowPwd ? 'password' : 'text'} suffix={password &&
                <img src={getImageUrl(
                    isShowPwd ? 'ic_eye_stop.png' : 'ic_eye.png')}
                     style={{width: '20px', height: '20px', cursor: 'pointer'}}
                     onClick={() => {
                       setIsShowPwd(!isShowPwd);
                     }}/>}></MInput>
          </Form.Item> : <Form.Item
              name="code"
              validateTrigger="onBlur"
              style={{marginBottom: '41px'}}
              rules={[
                {required: true, message: '验证码不能为空'},
                {
                  validator: (_, value) => {
                    // const notNumberReg = /[^\d]+/g
                    const vertificationCodeReg = /^[\d]{6}$/g; //验证码验证正则表达式
                    // if (value && notNumberReg.test(value)) {
                    //   form.setFieldValue(['code'], value.replace(notNumberReg, ''))
                    //   return Promise.reject(new Error('您输入的验证码错误，请重新输入'));
                    // }
                    if (value && !vertificationCodeReg.test(value)) {
                      return Promise.reject(
                          new Error('您输入的验证码错误，请重新输入'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-message" placeholder="请输入短信验证码"
                    maxLength={6}
                    suffix={<CodeBtn isSendCode={isSendCode}
                                     countDown={countDown}
                                     sendCode={sendCode}/>}></MInput>
          </Form.Item>}

          <div className="login-btn" onClick={handleLogin}>登录</div>
          <div className="operator">
            {activeTab === 1 &&
                <Checkbox checked={rememberPassword} onChange={(e) => {
                  setRememberPassword(e.target.checked);
                }}><span className="label">记住密码</span></Checkbox>}

            <div className="tips" style={{justifyItems: 'flex-end'}}>
              <div className="tips-item" onClick={() => {
                navigate('/register');
              }}>注册新用户
              </div>
              <div className="tips-item" onClick={() => {
                navigate('/forget');
              }}>忘记密码？
              </div>
            </div>
          </div>
        </Form>
      </LoginFormContainer>
    </LoginLayout>
  </>);
}

export default LoginPage;